package com.cnbot.dchttpsdk.rx;

import android.content.Context;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.cnbot.dchttpsdk.R;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import retrofit2.adapter.rxjava.HttpException;
import rx.Subscriber;

/**
 * Copyright (c) 2016-a  Hunan Cnbot Co., Ltd. All Rights Reserved.
 *
 * @descriptoin rx基类
 * @FileName: BaseSubscriber.java
 * @author: dc
 * @date: 2019/1/19 14:09
 * @version: 1.0
 */

public abstract class BaseSubscriber<T> extends Subscriber<T> {
    private final String TAG = "BaseSubscriber";

    protected Context mContext;

    public BaseSubscriber(Context context) {
        this.mContext = context;

    }

    protected boolean inMainThread() {
        return Looper.getMainLooper() == Looper.myLooper();
    }

    @Override
    public void onCompleted() {
        Log.v(TAG, "onCompleted");
    }

    /**
     * 对错误进行统一处理
     * 隐藏ProgressDialog
     *
     * @param e
     */
    @Override
    public void onError(Throwable e) {
        Log.v(TAG, "onError " + e.getMessage());
        if (e instanceof SocketTimeoutException) {
            Toast.makeText(mContext, mContext.getString(R.string.net_timeout_exception), Toast.LENGTH_LONG).show();
        } else if (e instanceof ConnectException) {
            Toast.makeText(mContext, mContext.getString(R.string.net_connect_exception), Toast.LENGTH_LONG).show();
        } else if (e instanceof HttpException) {
            Toast.makeText(mContext, mContext.getString(R.string.http_request_exception), Toast.LENGTH_LONG).show();
        }
        else {
            Toast.makeText(mContext, e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

}